package com.intellif.bio;

import com.intellif.utils.NamedThreadFactory;
import com.intellif.utils.Utils;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author by mozping
 * @Classname BioServer
 * @Description BIO 服务端，负责监听端口，接受客户端的连接
 * @Date 2019/4/22 12:43
 */
public class BioServer {

    private static final int PORT = Utils.PORT;
    private static ServerSocket serverSocket;

    /**
     * 执行任务的线程池
     */
    private static ExecutorService executorService = new ThreadPoolExecutor(
            5,
            10,
            10L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(20),
            new NamedThreadFactory()
    );


    private static void start() throws Exception {
        try {
            //1.绑定端口
            serverSocket = new ServerSocket(PORT);
            System.out.println("Bio server start , the port listening is : " + PORT);
            while (true) {
                //1.服务端等待socket上客户端的连接，注意这个方法会一直阻塞直到有连接位置
                Socket accept = serverSocket.accept();
                System.out.println("New connection established ...,ready to execute the task... ");
                //2.将建立的连接交给线程处理，因此一个连接需要一个线程处理
                executorService.execute(new BioServerHandler(accept));
            }
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        start();
    }
}
